package com.sofwin.ex;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sofwin.entity.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @packageName: com.sofwin.ex
 * @author: andyliu
 * @date: 2022/5/23 10:51
 * @email 115176513@qq.com
 * @description: TODO
 */
public class MyException implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        PrintWriter writer = httpServletResponse.getWriter();
        if(e instanceof FlowException){
            ResponseEntity result = new ResponseEntity();
            result.setCode(500);
            result.setMsg("对不起，被流控了");
            ObjectMapper mapper = new ObjectMapper();
            writer.write(mapper.writeValueAsString(result));
        }
        if(e instanceof ParamFlowException){
            ResponseEntity result = new ResponseEntity();
            result.setCode(500);
            result.setMsg("对不起，热点规则流控");
            ObjectMapper mapper = new ObjectMapper();
            writer.write(mapper.writeValueAsString(result));
        }
        if(e instanceof DegradeException){
            ResponseEntity result = new ResponseEntity();
            result.setCode(500);
            result.setMsg("对不起，服务被降级了");
            ObjectMapper mapper = new ObjectMapper();
            writer.write(mapper.writeValueAsString(result));
        }
    }
}
